package com.wyj.rpc.config;

import com.alibaba.fastjson.JSONObject;
import com.wyj.rpc.common.RpcRequest;
import com.wyj.rpc.common.RpcResponse;
import com.wyj.rpc.config.RpcClient;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.*;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * TODO: rpc服务的代理类。
 *  生成rpc服务的代理类，实现具体的服务调用，包括：
 *      1、rpc参数封装；
 *      2、创建RpcClient对象，实现
 *
 * @author wuyijie
 * @date 2021/12/26 1:44 下午
 */
public class RpcServiceProxy {
    //存放所有的netty服务端信息
    // private static Map<InetSocketAddress, String> socketAddressMap = new HashMap();
    // private static Map<Integer, RpcClient> rpcClientMap = new TreeMap<>();

    // private static AtomicInteger currentRpcClientKey = new AtomicInteger(0);
    // private static AtomicInteger rpcClientNum = new AtomicInteger(0);

    public static Object createProxy(Class<?> serviceClazz) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClazz},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        // rpc参数封装；
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setServiceName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setParameters(args);

                        //发送请求
                        RpcClient rpcClient=RpcClient.getInstance();
                        Object result = rpcClient.sendRequest(JSONObject.toJSONString(rpcRequest));
                        // rpcClient.close();
                        RpcResponse rpcResponse = JSONObject.parseObject(result.toString(), RpcResponse.class);
                        if (null != rpcResponse.getErrorMsg()) {
                            throw new RuntimeException(rpcResponse.getErrorMsg());
                        }
                        // 返回结果
                        return JSONObject.parseObject(rpcResponse.getData().toString(), method.getReturnType());
                    }
                });
    }
}
